package com.example.victory.mapper;

import com.example.victory.swagger.model.ApiResponseCrmUserIdData;
import com.example.victory.swagger.model.ApiResponseCrmUsersInfoData;
import com.example.victory.swagger.model.CrmJjrbh;
import com.example.victory.swagger.model.CrmUser;
import org.apache.ibatis.annotations.*;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;

import java.util.List;

@Mapper
@CacheConfig(cacheNames = {"inner-business-customer"})
public interface UserMapper {
    @Results(id = "userResultMap", value = {
            @Result(property = "role.id", column = "roleid"),
            @Result(property = "role.name", column = "rolename"),
            @Result(property = "org.id", column = "orgid"),
            @Result(property = "org.orgcode", column = "orgcode"),
            @Result(property = "org.name", column = "orgname"),
            @Result(property = "org.orgtype", column = "orgtype"),
    })
    @Select("select u.id,u.userid,r.rybh,r.id as crmid,u.name,u.phone,r.zjlb,r.zjbh as idcode,f.FLMC as rolename,f.id as roleid,o.id as orgid,o.orgcode,o.name as orgname,o.orgtype from CRMII.TUSER u \n" +
            "left join CRMII.TRYXX r on u.ID=r.DYYH\n" +
            "left join CRMII.TRYJBXX j on j.RYXX=r.ID\n" +
            "left join CRMII.TRYFLBM f on j.RYFL=f.ID\n" +
            "left join CRMII.LBORGANIZATION o on u.ORGID=o.id\n" +
            "where u.zt=0")
    List<CrmUser> findUsers();

    @Select({"SELECT RY.id ,KH.KHH as customerId " +
            " FROM CRMII.TKHXX KH, CRMII.TKHGX KHGX, CRMII.TRYXX RY  " +
            " WHERE KH.ID = KHGX.KHH " +
            "  AND RY.ID = KHGX.RYXX AND KHGX.GXLX = 2 AND KHGX.ZT = 0  " +
            "  AND KH.KHH = #{customerId} "})
    ApiResponseCrmUsersInfoData findUsersByCustomerId(@Param(value = "customerId") String customerId);

    @Cacheable(key = "'customer:dept:accountId:'+#p0", unless = "#result==null")
    @Select({"SELECT YH.USERID as userId,YH.NAME as name,lb.NAME as departmentName,lb.id as departmentCode,RY.RYBH as userNum  " +
            " FROM CRMII.TRYXX RY, CRMII.TUSER YH,CRMII.lborganization lb   " +
            "  WHERE RY.DYYH = YH.ID  AND  lb.ID=RY.orgid  " +
            "  AND RY.ID = #{tryxxId} "})
    ApiResponseCrmUserIdData findUsersIdByTryxxId(@Param(value = "tryxxId") String tryxxId);
   
    @Select({"SELECT count(1) FROM CRMII.TRYXX RY, CRMII.TUSER YH, CRMII.TRYJBXX JB WHERE RY.DYYH = YH.ID  AND RY.ID = JB.RYXX   AND JB.RYFL IN (7,19,20,21,22) AND JB.ZT = 0 AND yh.userid=#{userId} "})
    int getBrokersClientsByUserId(@Param(value = "userId") String userId);

    // 只取这个 jjrzt 是1,3的，其他值是离职或者错误数据的，目前发现对应有些二维码系统的编号有数据，但jjrzt 是5,黄宁那边说是错误数据，应该要更新二维码
    @Select("SELECT jjrbh, tryxx_id crmId FROM CRMII.TJJR WHERE JJRZT IN (1, 3) AND tryxx_id IS NOT NULL")
    List<CrmJjrbh> findCrmJjrbh();
}
